package com.zzyl.nursing.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.core.domain.entity.SysUser;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.framework.config.properties.HuaWeiIotConfigProperties;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.service.IDeviceService;
import com.zzyl.nursing.vo.DeviceDetailVo;
import com.zzyl.nursing.vo.ProductSummaryVo;
import com.zzyl.system.service.ISysUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 设备Service业务层处理
 * 
 * @author yjr
 * @date 2025-05-25
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService
{
    @Autowired
    private DeviceMapper deviceMapper;

    /**
     * 查询设备
     * 
     * @param id 设备主键
     * @return 设备
     */
    @Override
    public Device selectDeviceById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询设备列表
     * 
     * @param device 设备
     * @return 设备
     */
    @Override
    public List<Device> selectDeviceList(Device device)
    {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备
     * 
     * @param device 设备
     * @return 结果
     */
    @Override
    public int insertDevice(Device device)
    {
        return save(device) ? 1 : 0;
    }

    /**
     * 修改设备备注名称
     * 
     * @param dto 设备
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateDevice(DeviceDto dto)
    {
        Long count = this.lambdaQuery()
                .eq(Device::getBindingLocation, dto.getBindingLocation())
                .eq(Device::getLocationType, dto.getLocationType())
                .eq(Device::getProductKey, dto.getProductKey())
                .count();
        Long count1 = this.lambdaQuery()
                .eq(Device::getBindingLocation, dto.getBindingLocation())
                .eq(Device::getLocationType, dto.getLocationType())
                .eq(Device::getProductKey, dto.getProductKey())
                .eq(Device::getDeviceName, dto.getDeviceName())
                .count();
        if (count>0 && count1<1){
            throw new BaseException("设备名称重复");
        }

        if (dto == null){
            throw new BaseException("参数异常");
        }

        Device device=new Device();
        device.setId(dto.getId());
        device.setPhysicalLocationType(dto.getPhysicalLocationType());
        device.setDeviceDescription(dto.getDeviceDescription());
        device.setBindingLocation(dto.getBindingLocation());
        device.setLocationType(dto.getLocationType());
        device.setRemark(dto.getRemark());
        device.setNickname(dto.getRegisterDeviceRequest().getNickname());

        boolean result = this.updateById(device);
        if (!result){
            throw new BaseException("修改失败");
        }

        UpdateDeviceRequest request = new UpdateDeviceRequest();
        request.withDeviceId(dto.getIotId());
        UpdateDevice body = new UpdateDevice();
        body.setDeviceName(dto.getDeviceName());
        body.withDescription(dto.getRegisterDeviceRequest().getNickname());
        request.withBody(body);

        UpdateDeviceResponse response = client.updateDevice(request);
        if (response==null || response.getHttpStatusCode()!=200){
            throw new BaseException("修改华为云设备失败");
        }
    }

    /**
     * 批量删除设备
     * 
     * @param ids 需要删除的设备主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除设备信息
     * 
     * @param iotId
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteDeviceByIotId(String iotId)
    {
        if (StringUtils.isBlank(iotId)){
            throw new BaseException("参数异常");
        }

        boolean result = this.remove(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, iotId));
        if (!result){
            throw new BaseException("删除失败");
        }

        DeleteDeviceRequest request = new DeleteDeviceRequest();
        request.withDeviceId(iotId);
        DeleteDeviceResponse response = client.deleteDevice(request);
        if (response.getHttpStatusCode()!=204){
            throw new BaseException("删除华为云设备失败");
        }
    }

    @Autowired
    private IoTDAClient client;
    @Autowired
    private StringRedisTemplate redis;

    /**
     * 从物联网平台同步产品列表
     */
    @Override
    public void syncProductList() {
        //1.从华为云中获取数据
        ListProductsResponse response = client.listProducts(new ListProductsRequest());
        if (response==null||response.getHttpStatusCode()!=200){
            throw new BaseException("获取失败");
        }

        //2.存入redis
        List<ProductSummary> productSummaryList = response.getProducts();
        redis.opsForValue().set(CacheConstants.IOT_PRODUCT_LIST_KEY, JSONUtil.toJsonStr(productSummaryList));

    }

    /**
     * 查询所有产品列表
     *
     * @return
     */
    @Override
    public List<ProductSummaryVo> getAllProduct() {
        //1.从redis中取出数据
        String productSummaryListJson = redis.opsForValue().get(CacheConstants.IOT_PRODUCT_LIST_KEY);
        if (StringUtils.isBlank(productSummaryListJson)){
            throw new BaseException("产品列表为空");
        }

        //2.整理数据返回
        List<ProductSummary> productSummaryList = JSONUtil.toList(productSummaryListJson, ProductSummary.class);
        return productSummaryList.stream().map(x->ProductSummaryVo.of(x.getProductId(),x.getName())).collect(Collectors.toList());

    }


    /**
     * 注册设备
     *
     * @param dto
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void register(DeviceDto dto) {
        //1.设备名称是否重复
        Long countName = this.lambdaQuery()
                .eq( Device::getDeviceName, dto.getDeviceName())
                .count();
        if (countName>0){
            throw new BaseException("设备名称重复");
        }

        //2.同一位置是否绑定了相同的产品
        Long count = this.lambdaQuery()
                .eq(Device::getBindingLocation, dto.getBindingLocation())
                .eq(Device::getLocationType, dto.getLocationType())
                .eq(Device::getProductKey, dto.getProductKey())
                .count();
        if (count>0){
            throw new BaseException("设备名称重复");
        }

        //3.注册设备
        AddDeviceRequest requst = new AddDeviceRequest();
        AddDevice body = new AddDevice();
        String nodeId = IdUtil.getSnowflakeNextIdStr();
        String secret = IdUtil.fastSimpleUUID();
        body.setNodeId(nodeId);
        body.setProductId(dto.getProductKey());
        body.setDeviceName(dto.getDeviceName());
        String nickname = dto.getRegisterDeviceRequest().getNickname();
        body.setDescription(nickname);
        AuthInfo authInfo = new AuthInfo();
        authInfo.setSecret(secret);
        body.setAuthInfo(authInfo);

        requst.withBody(body);

        AddDeviceResponse response = client.addDevice(requst);
        if (response==null||response.getHttpStatusCode()!=201){
            throw new BaseException("注册失败");
        }

        //4.整合数据保存到本地
        Device device = new Device();
        BeanUtils.copyProperties(dto, device);
        device.setIotId(response.getDeviceId());
        device.setNodeId(nodeId);
        device.setSecret(secret);
        device.setNickname(nickname);
        device.setDeviceDescription(dto.getDeviceDescription());
        device.setProductName(getProductName(dto.getProductKey()).getName());

        boolean result = this.save(device);
        if (!result){
            throw new BaseException("添加信息注册失败");
        }

    }

    /**
     * 获取ProductName
     * @param productKey
     * @return
     */
    private ProductSummary getProductName(String productKey) {
        //1.从redis中取出数据
        String productSummaryListJson = redis.opsForValue().get(CacheConstants.IOT_PRODUCT_LIST_KEY);
        if (StringUtils.isBlank(productSummaryListJson)){
            throw new BaseException("产品列表为空");
        }

        //2.整理数据返回
        List<ProductSummary> productSummaryList =JSONUtil.toList(productSummaryListJson, ProductSummary.class);
        ProductSummary productSummary = productSummaryList.stream().filter(x -> x.getProductId().equals(productKey)).findFirst().get();
        return productSummary;
    }
    @Autowired
    private HuaWeiIotConfigProperties huaWeiIotConfigProperties;
    @Autowired
    private ISysUserService iSysUserService;

    /**
     * 查询设备详细信息
     *
     * @param iotId
     * @return
     */
    @Override
    public DeviceDetailVo queryDeviceDetail(String iotId) {
        //1.查看设备是否存在
        Device device = this.lambdaQuery().eq(Device::getIotId, iotId).one();
        if (device==null){
            throw new BaseException("设备不存在");
        }

        //2.整合数据到vo中
        DeviceDetailVo detailVo = new DeviceDetailVo();
        BeanUtils.copyProperties(device, detailVo);
        detailVo.setGmtCreate(device.getCreateTime());
        detailVo.setRegion(huaWeiIotConfigProperties.getRegionId());
        SysUser sysUser = iSysUserService.selectUserById(Long.valueOf(device.getCreateBy()));
        detailVo.setCreator(sysUser.getUserName());
        detailVo.setDeviceSecret(device.getSecret());

        //3.查询华为云设备详细信息
        ShowDeviceRequest request=new ShowDeviceRequest();
        request.withDeviceId(iotId);
        ShowDeviceResponse response = client.showDevice(request);
        if (response==null||response.getHttpStatusCode()!=200){
            throw new BaseException("设备不存在");
        }

        //4.补充vo信息
        detailVo.setDeviceStatus(response.getStatus());
        detailVo.setStatus(response.getStatus());
        String activeTime = response.getActiveTime();
        LocalDateTime gmtActive = null;
        if (StringUtils.isNotBlank(activeTime)) {
            gmtActive = OffsetDateTime.parse(activeTime).atZoneSameInstant(ZoneId.of("Asia/Shanghai")).toLocalDateTime();
        }
        detailVo.setGmtActive(gmtActive);
        detailVo.setFirmwareVersion(response.getFwVersion());

        //5.返回数据
        return detailVo;

    }

    /**
     * 查看指定产品的已发布物模型中的功能定义详情
     *
     * @param productKey
     * @return
     */
    @Override
    public JSONObject queryProductModelInfo(String productKey) {
        //1.在华为云上获取数据
        ShowProductRequest request = new ShowProductRequest();
        request.withProductId(productKey);
        ShowProductResponse response = client.showProduct(request);
        if (response==null||response.getHttpStatusCode()!=200){
            throw new BaseException("获取华为云数据失败");
        }

        //2.整理数据
        List<ServiceCapability> serviceCapabilities = response.getServiceCapabilities();
        if (serviceCapabilities.isEmpty()){
            throw new BaseException("获取华为云数据失败");
        }

        //3.转换为JSONObject返回
        ServiceCapability serviceCapability = serviceCapabilities.get(0);
        JSONObject jsonObject = JSONUtil.parseObj(serviceCapability);
        return jsonObject;
    }

    /**
     * 查询指定设备的物模型运行状态
     *
     * @param deviceName
     * @return
     */
    @Override
    public Map<String, Object> queryDevicePropertyStatus(String deviceName) {
        //1.查询设备是否存在
        Device device = this.lambdaQuery().eq(Device::getDeviceName, deviceName).select(Device::getIotId).one();
        if (device==null){
            throw new BaseException("查询设备不存在");
        }

        //2.在华为云查询ioTDA的设备影子
        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.withDeviceId(device.getIotId());
        ShowDeviceShadowResponse response = client.showDeviceShadow(request);
        if (response==null||response.getHttpStatusCode()!=200){
            throw new BaseException("在华为云查询ioTDA的设备影子失败");
        }

        //3.解析数据封装map
        List<DeviceShadowData> shadow = response.getShadow();
        DeviceShadowData deviceShadowData = shadow.get(0);
        DeviceShadowProperties reported = deviceShadowData.getReported();
        String eventTimeStr = reported.getEventTime();
        LocalDateTime eventTime = OffsetDateTime.parse(eventTimeStr, DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmssX"))
                .atZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                .toLocalDateTime();
        JSONObject jsonObject = JSONUtil.parseObj(reported.getProperties());
        List<Map<String,Object>> list=new ArrayList<>();
        jsonObject.forEach((k,v)->{
            Map<String,Object> map =new HashMap<>();
            map.put("identifier", k);
            map.put("name", k);
            map.put("time", eventTime);
            map.put("value", v);
            list.add(map);
        });

        //4.返回封装数据
        Map<String,Object> resultMap =new HashMap<>();
        Map<String,Object> propertyStatusInfoMap =new HashMap<>();
        propertyStatusInfoMap.put("propertyStatusInfo", list);
        resultMap.put("list", propertyStatusInfoMap);

        return resultMap;
    }
}
